<template>
  <div id="prizeSetting">
    <el-form ref="ruleForm" :model="prizeList" :rules="rules" :inline="true">
      <el-form-item label="获奖收集时间" class="top-time" prop="createTime">
        <el-date-picker
          v-model="prizeList.createTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          :disabled="!showBtn"
        >
        </el-date-picker>
      </el-form-item>
      <div v-for="(item, index) in prizeList.awards" :key="index">
        <el-card class="cus-form-card" shadow="never">
          <el-row>
            <el-col :span="23">
              <el-form-item
                label="奖项名称"
                :prop="'awards.' + index + '.name'"
                :rules="rules.name"
              >
                <el-input
                  v-model.trim="item.name"
                  placeholder="奖项名称"
                  maxlength="60"
                  show-word-limit
                  :disabled="saved[index] || !showBtn"
                ></el-input>
              </el-form-item>
              <el-form-item
                class="small"
                label="奖项数量"
                :prop="'awards.' + index + '.prizeAmount'"
                :rules="rules.prizeAmount"
              >
                <el-input-number
                  v-model.number="item.prizeAmount"
                  :disabled="saved[index] || !showBtn"
                  size="mini"
                  :min="0"
                  :max="999999"
                  :controls="false"
                ></el-input-number>
                个
              </el-form-item>
              <el-form-item label="获奖名单导入">
                <el-button
                  type="primary"
                  @click="importBtn(item.id)"
                  :disabled="!showBtn || !item.id"
                >
                  导入
                </el-button></el-form-item
              >
              <el-form-item label="">
                当前：{{ item.userCount }}个用户
              </el-form-item>
            </el-col>
            <el-col :span="1">
              <!--删除-->
              <i
                v-if="showBtn && prizeList.awards.length > 1"
                class="cus-iconSize el-icon-delete"
                @click="delCard(index)"
              ></i>
            </el-col>
          </el-row>
          <dl>
            <dt class="group-title">
              奖品名称（奖品名称每增加一条，前端增加对应奖品类型选项，如：实物奖品4个，则实物奖品为4选1）
            </dt>
            <!--实物奖品-->
            <dd
              v-for="(item2, index2) in item.entityPrizes"
              :key="index2"
              class="cus-card-item"
            >
              <el-form-item
                :label="`实物奖品${index2 + 1}:`"
                :prop="'awards.' + index + '.entityPrizes.' + index2 + '.name'"
                :rules="rules.prizeName"
              >
                <el-input
                  v-model.trim="item2.name"
                  maxlength="60"
                  show-word-limit
                  :disabled="saved[index] || !showBtn"
                  placeholder="奖品名称"
                ></el-input>
              </el-form-item>
              <el-form-item class="small" label="单价:">
                <el-input-number
                  v-model.number="item2.money"
                  :disabled="saved[index] || !showBtn"
                  size="mini"
                  :min="0"
                  :max="999999"
                  :controls="false"
                ></el-input-number>
                元
              </el-form-item>
              <el-form-item
                label="备注:"
                :prop="
                  'awards.' + index + '.entityPrizes.' + index2 + '.remark'
                "
                :rules="rules.remark"
              >
                <el-input
                  v-model.trim="item2.remark"
                  maxlength="60"
                  show-word-limit
                  :disabled="saved[index] || !showBtn"
                ></el-input>
              </el-form-item>
              <el-form-item label="">
                <!--新增实物奖品-->
                <i
                  v-if="showBtn"
                  class="cus-iconSize el-icon-circle-plus-outline"
                  @click="addLine(index, index2, 'entityPrizes')"
                ></i>
                <!--删除实物奖品-->
                <i
                  v-if="showBtn && item.entityPrizes.length > 1"
                  class="cus-iconSize el-icon-remove-outline"
                  @click="delLine(index, index2, 'entityPrizes')"
                ></i>
              </el-form-item>
            </dd>
            <dd class="real-box"></dd>
            <!--虚拟奖品-->
            <dd
              v-for="(item2, index2) in item.virtualPrizes"
              :key="`${index2}_xn`"
              class="cus-card-item"
            >
              <el-form-item
                :label="`虚拟奖品${index2 + 1}:`"
                :prop="'awards.' + index + '.virtualPrizes.' + index2 + '.name'"
                :rules="rules.prizeName"
              >
                <el-input
                  v-model.trim="item2.name"
                  maxlength="60"
                  show-word-limit
                  :disabled="saved[index] || !showBtn"
                  placeholder="奖品名称"
                ></el-input>
              </el-form-item>
              <el-form-item class="small" label="单价:">
                <el-input-number
                  v-model.number="item2.money"
                  :disabled="saved[index] || !showBtn"
                  size="mini"
                  :min="0"
                  :max="999999"
                  :controls="false"
                ></el-input-number>
                元
              </el-form-item>
              <el-form-item
                label="备注:"
                :prop="
                  'awards.' + index + '.virtualPrizes.' + index2 + '.remark'
                "
                :rules="rules.remark"
              >
                <el-input
                  v-model.trim="item2.remark"
                  maxlength="60"
                  show-word-limit
                  :disabled="saved[index] || !showBtn"
                ></el-input>
              </el-form-item>
              <el-form-item label="">
                <!--新增虚拟-->
                <i
                  v-if="showBtn"
                  class="cus-iconSize el-icon-circle-plus-outline"
                  @click="addLine(index, index2, 'virtualPrizes')"
                ></i>
                <!--删除虚拟-->
                <i
                  v-if="showBtn && item.virtualPrizes.length > 1"
                  class="cus-iconSize el-icon-remove-outline"
                  @click="delLine(index, index2, 'virtualPrizes')"
                ></i>
              </el-form-item>
            </dd>
          </dl>
          <div class="card-btn-box">
            <el-button
              v-if="showBtn"
              type="success"
              @click="changeStatue(index, true)"
            >
              保存
            </el-button>
            <el-button
              v-if="showBtn"
              type="primary"
              @click="changeStatue(index, false)"
              :disabled="!showBtn"
            >
              修改
            </el-button>
          </div>
        </el-card>
      </div>
      <el-button
        v-if="showBtn"
        type="success"
        icon="el-icon-plus"
        @click="addCard"
      >
        添加奖项
      </el-button>
      <el-row>
        <el-form-item label="发奖链接">
          <el-input
            class="link-input"
            v-model.trim="prizeList.url"
            :disabled="true"
          ></el-input>
        </el-form-item>
      </el-row>
    </el-form>
    <div v-if="showBtn" class="btn-box">
      <el-button plain @click="cancelLabel">
        取 消
      </el-button>
      <el-button
        type="success"
        :loading="loading"
        @click="confirmLabel('ruleForm')"
      >
        保存
      </el-button>
      <el-button type="primary" @click="nextLab('touchSetting')">
        上一步
      </el-button>
      <el-button type="primary" @click="nextLab('allocatedManage')">
        下一步
      </el-button>
    </div>
    <!-- 导入弹窗 -->
    <importDialog
      v-if="importDialogData.isShow"
      :dialog-data="importDialogData"
      @refresh="getUserNum"
      @showError="showError"
    ></importDialog>
    <!-- 导入失败弹窗 -->
    <errorDialog
      v-if="errorDialogData.isShow"
      :dialog-data="errorDialogData"
      from="prizeSetting"
    ></errorDialog>
  </div>
</template>

<script>
import {
  savePrize,
  editPrize,
  downUrl,
  importUrl
} from '@/api/activeManagement/templatePage' // 接口
import importDialog from '@common/importDialog' // 导入弹窗
import errorDialog from '@common/errorDialog' // 导入失败弹窗
import { clearTagMixins } from '@/mixins/clearTag'
export default {
  name: 'prizeSetting',
  msg: '奖品配置',
  mixins: [clearTagMixins],
  props: ['type', 'prizeLists', 'backPage', 'id'],
  components: {
    importDialog,
    errorDialog
  },
  data() {
    return {
      isSave: false,
      loading: false,
      showBtn: true,
      createTime: [],
      prizeList: {},
      lineData: { name: '', money: '0', remark: '' },
      cardData: {
        name: '',
        prizeAmount: '',
        userCount: '0',
        entityPrizes: [{ name: '', money: '0', remark: '' }],
        virtualPrizes: [{ name: '', money: '0', remark: '' }]
      },
      rules: {
        createTime: {
          required: true,
          message: '获奖收集时间不能为空',
          trigger: 'blur'
        },
        name: [
          {
            required: true,
            message: '奖项名称不能为空',
            trigger: 'blur'
          },
          { max: 60, message: '长度不超过60', trigger: 'blur' }
        ],
        prizeAmount: [
          {
            required: true,
            message: '奖项数量不能为空',
            trigger: 'blur'
          }
        ],
        prizeName: { max: 60, message: '长度不超过60', trigger: 'blur' },
        remark: { max: 60, message: '长度不超过60', trigger: 'blur' },
        money: {}
      },
      // 传递给导入弹框的数据
      importDialogData: {
        title: '导入获奖名单',
        isShow: false, // 控制弹框显示
        url: '', // 导入接口
        downUrl: '' // 下载模板接口
      },
      // 导入失败弹框的数据
      errorDialogData: {
        isShow: false, // 控制弹框显示
        warningText: '' // 参数
      },
      saved: [] //记录card是否执行保存
    }
  },
  watch: {
    'prizeList.createTime': {
      handler(newVal, oldVal) {
        if (newVal && newVal.length > 1) {
          this.prizeList.startDate = newVal[0]
          this.prizeList.endDate = newVal[1]
        } else {
          this.prizeList.startDate = ''
          this.prizeList.endDate = ''
        }
      },
      deep: true
    },
    prizeLists: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.prizeList = JSON.parse(JSON.stringify(newVal))
          this.init()
        }
      },
      deep: true
    }
  },
  mounted() {},
  methods: {
    init() {
      let n = this.prizeList.awards.length
      for (let i = 0; i < n; i++) {
        this.saved.push(false)
      }
      //实物奖品、虚拟奖品为空时，赋默认值
      this.setDefaultLine()
      //showBtn赋值
      if (this.type === 'check') {
        this.showBtn = false
      } else {
        if (this.prizeList.id) {
          let nowDate = new Date().getTime()
          let start = this.createTime[0] || this.prizeList.startDate
          let startData = new Date(start).getTime()
          this.showBtn = nowDate < startData ? true : false
        } else {
          this.showBtn = true
        }
      }
    },
    /*实物奖品、虚拟奖品为空时，赋默认值*/
    setDefaultLine() {
      this.prizeList.awards.forEach((cur, index) => {
        if (!cur.entityPrizes) {
          cur.entityPrizes = [this.lineData]
        }
        if (!cur.virtualPrizes) {
          cur.virtualPrizes = [this.lineData]
        }
      })
    },
    resetIsSave() {
      this.isSave = false
    },
    /*新增虚拟/实物奖品*/
    addLine(index, index2, field) {
      if (this.saved[index]) return
      this.prizeList.awards[index][field].splice(index2 + 1, 0, {
        ...this.lineData
      })
    },
    /*删除虚拟/实物奖品*/
    delLine(index, index2, field) {
      if (this.saved[index]) return
      this.prizeList.awards[index][field].splice(index2, 1)
    },
    /*添加奖项*/
    addCard() {
      let data = JSON.parse(JSON.stringify(this.cardData))
      this.prizeList.awards.push(data)
      this.saved.push(false)
    },
    /*删除奖项*/
    delCard(index) {
      if (this.saved[index]) return
      this.prizeList.awards.splice(index, 1)
      this.saved.splice(index, 1)
    },
    /*当前奖项内容置灰/可编辑*/
    changeStatue(index, statue) {
      this.$set(this.saved, index, statue)
    },
    // 导入
    importBtn(id) {
      this.importDialogData.url = importUrl(this.prizeList.id, id) // 导入接口
      this.importDialogData.downUrl = downUrl() // 下载模板接口
      this.importDialogData.isShow = true // 显示导入弹框
    },
    /* 导入失败弹窗 */
    showError(text) {
      this.errorDialogData.isShow = true // 显示导入失败弹框
      this.errorDialogData.warningText = text // 显示导入失败弹框
    },
    /* 导入成功后，获取当前用户 */
    getUserNum() {
      this.$emit('getPrizeList')
    },
    /*取消*/
    cancelLabel() {
      if (this.isSave) {
        this.clearTag()
      } else {
        this.$confirm(
          '您的信息尚未保存，取消后所填写的信息将不被保存，确定要退出？',
          '提示',
          {
            distinguishCancelAndClose: true,
            confirmButtonText: '保存后退出',
            cancelButtonText: '直接退出',
            type: 'warning'
          }
        )
          .then(() => {
            this.confirmLabel('ruleForm').then((response) => {
              this.clearTag()
            })
          })
          .catch((action) => {
            if (action === 'cancel') {
              this.clearTag()
            }
          })
      }
    },
    /*退出*/
    signOut() {
      this.$router.go(-1)
      // let query = {
      //   mId: this.$route.query.mId
      // }
      // this.$router.replace({ name: this.backPage, query: query })
    },
    //处理提交方法
    packageParams() {
      let obj = JSON.parse(JSON.stringify(this.prizeList))
      for (let index = 0; index < this.prizeList.awards.length; index++) {
        let cur = this.prizeList.awards[index]
        let prizes = []
        let entityPrizes = [...cur.entityPrizes]
        let virtualPrizes = [...cur.virtualPrizes]
        for (let item of entityPrizes) {
          if (item.name) {
            if (item.money === undefined) {
              this.$message.warning('奖品价格不能为空！')
              return ''
            }
            item.type = 'ENTITY'
            prizes.push(item)
          }
        }
        for (let item of virtualPrizes) {
          if (item.name) {
            if (item.money === undefined) {
              this.$message.warning('奖品价格不能为空！')
              return ''
            }
            item.type = 'VIRTUAL'
            prizes.push(item)
          }
        }
        if (prizes.length === 0) {
          this.$message.warning('奖品名称不能为空！')
          return ''
        }
        obj.awards[index].prizes = prizes
        delete obj.awards[index].entityPrizes
        delete obj.awards[index].virtualPrizes
      }
      delete obj.createTime
      obj.relevanceId = this.id
      return obj
    },
    saveList() {
      let _this = this
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            let obj = this.packageParams()
            if (!obj) return
            _this.loading = true
            if (!_this.prizeList.id) {
              //新增
              savePrize(
                obj,
                (response) => {
                  _this.prizeList = response
                  _this.$set(_this.prizeList, 'createTime', [
                    response.startDate,
                    response.endDate
                  ])
                  _this.$store.commit('setPrizeId', {
                    activeId: this.id,
                    prizeId: response.id
                  })
                  //实物奖品、虚拟奖品为空时，赋默认值
                  _this.setDefaultLine()
                  _this.loading = false
                  _this.isSave = true
                  resolve(true)
                },
                (response) => {
                  this.loading = false
                  let message = response.message || '新增失败'
                  this.$message.warning(message)
                  reject()
                }
              )
            } else {
              //编辑
              editPrize(
                obj,
                (response) => {
                  _this.$message.success('保存成功')
                  this.$emit('getPrizeList')
                  _this.loading = false
                  _this.isSave = true
                  resolve(true)
                },
                (response) => {
                  this.$message.warning(response.message)
                  this.$emit('getPrizeList')
                  this.loading = false
                  reject()
                }
              )
            }
          } else {
            return false
          }
        })
      })
    },
    /*保存*/
    confirmLabel(formName) {
      let _this = this
      return new Promise((resolve, reject) => {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            let obj = this.packageParams()
            if (!obj) return
            _this.loading = true
            if (!_this.prizeList.id) {
              //新增
              savePrize(
                obj,
                (response) => {
                  _this.prizeList = response
                  _this.$set(_this.prizeList, 'createTime', [
                    response.startDate,
                    response.endDate
                  ])
                  _this.$store.commit('setPrizeId', {
                    activeId: this.id,
                    prizeId: response.id
                  })
                  //实物奖品、虚拟奖品为空时，赋默认值
                  _this.setDefaultLine()
                  _this.loading = false
                  _this.isSave = true
                  resolve(true)
                },
                (response) => {
                  this.loading = false
                  let message = response.message || '新增失败'
                  this.$message.warning(message)
                  reject()
                }
              )
            } else {
              //编辑
              editPrize(
                obj,
                (response) => {
                  _this.$message.success('保存成功')
                  this.$emit('getPrizeList')
                  _this.loading = false
                  _this.isSave = true
                  resolve(true)
                },
                (response) => {
                  this.$message.warning(response.message)
                  this.$emit('getPrizeList')
                  this.loading = false
                  reject()
                }
              )
            }
          } else {
            return false
          }
        })
      })
    },
    /*下一步*/
    nextLab(labName) {
      this.confirmLabel('ruleForm').then((response) => {
        this.$emit('changeLab', labName)
      })
    }
  }
}
</script>

<style lang="less">
#prizeSetting {
  overflow: auto;
  .el-form {
    .top-time {
      margin-bottom: 15px;
    }
    .el-range-separator,
    .el-range__icon,
    .el-range__close-icon {
      box-sizing: content-box;
      line-height: 25px;
    }
    .el-card {
      background-color: #f2f4f5;
      width: 850px;
      margin-bottom: 20px;
      .el-card__body {
        padding-right: 0;
      }
      .el-form-item {
        margin-bottom: 10px;
      }
      .el-form-item__error {
        padding-top: 0;
      }
      dt {
        font-size: 14px;
        color: #0d1636;
        padding: 15px 0 15px;
      }
      dd {
        margin-left: 20px;
      }
      .el-input {
        .el-input__inner {
          padding: 0 46px 0 8px;
        }
      }
    }
    .real-box {
      border-bottom: 1px dashed #ccc;
      margin: 10px 0 15px;
    }
    .prizeNum {
      width: 190px;
      .el-input {
        width: 80px;
        margin-right: 5px;
      }
    }
    .small {
      .el-input-number--mini {
        width: 70px;
        margin-right: 5px;
        .el-input__inner {
          padding-left: 5px;
          padding-right: 5px;
        }
      }
    }
    .cus-iconSize {
      color: #99a9bf;
      font-size: 20px;
      margin-right: 5px;

      &:hover {
        cursor: pointer;
        color: #0d1636;
      }
    }
    .link-input.el-input {
      width: 400px;
    }
    .card-btn-box {
      text-align: center;
      padding-top: 20px;
    }
  }
}
</style>
